/**
 *
 */
$(function() {

    $('#wr-rightcontent').on('click', 'button.cancel', function(e) {
        $('#edit-record').html('').addClass('ui-helper-hidden');
        $('#browse-records').removeClass('ui-helper-hidden');
    });
    

    /**
     * @see negative logic
     */
    
    $('#wr-rightcontent').on('click', '.trigger-toggle', function(e) {
    	var _fprefix = $(this).data('fprefix');
        var $related = $('#'+_fprefix +'-'+ $(this).data('related'));
        var $relatedalt = $('#' +_fprefix +'-'+ $(this).data('relatedalt'));

        if($(this).hasClass('onchecked')) {
            $related.closest('li').toggleClass('ui-helper-hidden-accessible', $(this).is(':checked') != true);
            $relatedalt.closest('li').toggleClass('ui-helper-hidden-accessible', $(this).is(':checked') != true);
        }
    });
    

    $('#wr-rightcontent').on('click', 'button.form-trigger', function(e) {
        _formError = 0;

        var _formid = $(this).data('formid');
        var _action = $('#' + _formid).data('action');

        if(_preventClick == 1) {
            e.preventDefault();
            return false;
        }

        $('#' + _formid + ' .required:not(label)').each(function() {
            /*$(this).qtip('destroy');*/

            var $label = $(this).parent().parent().find('label:first');

            $label.removeClass('ui-state-error-text');

            var _errorMessage = '';
            if($(this).val() == '') {
                // display tipsy
                _errorMessage = 'Required Field';
                _formError = 1;
            }

            if($(this).hasClass('val-email') && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i.test($(this).val())) {
                // display tipsy
                _errorMessage = 'Please enter valid e-mail';
                _formError = 1;
            }

            if($(this).hasClass('val-number') && !parseInt($(this).val())) {
                // display tipsy
                _errorMessage = 'Required Field';
                _formError = 1;
            }

            if(_errorMessage) {
                /*
                 $(this).qtip({
                 overwrite: false,
                 content: _errorMessage,
                 hide: false,
                 show: {
                 event: false,
                 ready: true
                 },
                 position: {
                 my: 'left center',
                 at: 'right center'
                 },
                 style: {
                 classes: 'ui-tooltip-shadow ui-tooltip-red',
                 widget: true
                 }
                 });
                 */
                $label.addClass('ui-state-error-text');
            }

        });
        if(_formError) {
            // @todo: console.log("some error");
            var _errormsg = {
                "header" : "Error",
                "message" : "Please enter values for required form fields",
                "error" : "1"
            };
            showDialog(_errormsg, false);
            e.preventDefault();
            return false;

        }

        $('#' + _formid + ' div.wysiwyg').each(function(v) {
            $(this).trigger('resync');
        });
        _data = $('#' + _formid).serialize();
        console.log("Serialized_data : %s", _data);

        $.ajax({
            data : _data,
            url : _urlbegin + '/' + _action + '-' + _request + '/' + _urlend + _ajax,
            type : 'post',
            dataType : 'json',
            beforeSend : function() {
                _preventClick = 1;
            },
            complete : function() {
                _preventClick = 0;
            },
            success : function(json) {
                console.log("here1");
                showDialog(json, true);
                console.log("here");
                $('#' + _formid + ' .file-upload').val('');
            }
        });

        e.preventDefault();

    });

    $('#browse-records .datatable').on('click', '.tk-trigger', function(e) {
        var $action = $(this).data('action');
        var $id = $(this).data('id');
        var $value = $(this).data('value');
        var $request = $(this).data('request');
        var $this = $(this);

        if(_preventClick == 1) {
            return false;
        }
        if($id == '') {
            // @todo module error
            return false;
        }

        if($action == 'edit' || $action == 'delete') {
            _data = '';
        }

        if($action == 'toggle') {
            _data = 'toggle=' + $value + '&';
        }
        $.ajax({
            data : _data + 'id=' + $id,
            url : _urlbegin + '/' + $action + '-' + $request + '/' + _urlend + _ajax,
            type : 'get',
            beforeSend : function() {
                _preventClick = 1;
            },
            success : function(html) {
                /* @todo: error */
                if($action == 'edit') {
                    $('#browse-records').addClass('ui-helper-hidden');
                    $('#edit-record').removeClass('ui-helper-hidden').html(html);
                }
                if($action == 'toggle') {
                    if($value == '1') {
                        $this.removeClass('active-input').addClass('inactive-input');
                        $this.data('value', '0');
                    }
                    if($value == '0') {
                        $this.removeClass('inactive-input').addClass('active-input');
                        $this.data('value', '1');
                    }

                }
                _preventClick = 0;
            }
        });

        e.preventDefault();
    });

    $('#save-data').on('click', '.trigger-imgremove', function(e) {

        var _target = $(this).data('target');
        $(this).hide();

        $('#' + _target).val('*delete*');
        $('#img-' + _target).prop('src', '').addClass('ui-helper-hidden');

        e.preventDefault();
    });

    $('#wr-rightcontent').on('keyup', 'input.check', function(e) {

        var $this = $(this);

        $.doTimeout($this.prop('id'), 2000, function() {

            var _fprefix = $this.data('fprefix');
            var _id = $this.data('id');

            var _check_field = $this.data('name');

            var $target = $('#check-' + _fprefix + '-' + _check_field);

            var _check_value = $this.val();

            _data = 'check=' + _check_field + '&v=' + _check_value + '&id=' + _id;

            $.ajax({
                global : false,
                url : _urlbegin + '/check-' + _request + '/' + _urlend + _ajax,
                data : _data,
                dataType : 'json',
                method : 'get',
                cache : false,
                beforeSend : function() {
                    $target.removeClass('sprite-accept sprite-cancel').addClass('sprite-loading');
                },
                success : function(json) {
                    if(!$.isPlainObject(json)) {
                        showDialog("error");
                    } else {
                        if(json.code == -1) {
                            $target.addClass('sprite-cancel');
                        } else {
                            $target.addClass('sprite-accept');
                        }
                    }

                },
                complete : function() {
                    $target.removeClass('sprite-loading');
                }
            });

        });
    });

    $('#wr-rightcontent').on('keyup click', '.generate-value', function(e) {

        var _fprefix = $(this).data('fprefix');
        var $related = $('#' + _fprefix + '-' + $(this).data('related'));
        var $relatedalt = $('#' + _fprefix + '-' + $(this).data('relatedalt'));


        if($(this).hasClass('onkeyup')) {
            var _value = $(this).val();
            _value = _value.toLowerCase().replace(/[^\w]+/ig, '_');

            if($relatedalt.length == 1) {

                if($relatedalt.is(':checked')) {
                    _value = _value + '_req';
                } else {
                    _value = _value.replace(/^(.+)_req$/ig, '$1');
                }
            }

        }

        if($(this).hasClass('onclick')) {

            var _value = $relatedalt.val();
            _value = _value.toLowerCase().replace(/[^\w]+/ig, '_');
            if($(this).is(':checked')) {
                _value = _value + '_req';
            } else {
                _value = _value.replace(/^(.+)_req$/ig, '$1');
            }
        };
        $related.val(_value);

        $related.trigger('keyup');

    });
});
